import { useMemo, useRef, useState } from "react";
import DescriptionBox from "../../components/DescriptionBox";

const UseMemoDemo = () => {
  const [count, setCount] = useState(0);
  const [number, setNumber] = useState(10);

  const computeExpensiveValue = (a: number, type: string) => {
    console.log("🚀 ~ computeExpensiveValue ~ i:", type);

    for (let i = 0; i < 10000000; i++) {
      // TODO
    }
    return a;
  };

  const renderCount = useMemo(() => {
    return computeExpensiveValue(count, 'count');
  }, [count]);

  const renderNumber = computeExpensiveValue(number, 'number');

  return <>
    <div>count: {count} ||| number: {number}</div>
    <div><button onClick={() => setCount(count + 1)}>Change count</button></div>
    <div><button onClick={() => setNumber(number + 1)}>Change number</button></div>
    <div>renderNumber: {renderNumber}</div>
    <div>renderCount: {renderCount}</div>
    <ClickCounter />
  </>;
};


function ClickCounter() {
  const countRef = useRef(0); // 初始值为 0
  const [displayCount, setDisplayCount] = useState(0); // 用于 UI 显示

  const handleClick = () => {
    // 更新 ref 的值（不会触发重新渲染）
    countRef.current += 1;
    console.log("🚀 ~ handleClick ~ countRef:", countRef);
    // 可选：更新 state 以触发 UI 更新
    setDisplayCount(countRef.current);
  };

  return (
    <div>
      <button onClick={handleClick}>
        点击我 ({displayCount})
      </button>
      <p>实际计数（ref）: {countRef.current}</p>

      <DescriptionBox items={['更新 ref 的值（不会触发重新渲染）',]}></DescriptionBox>
    </div>
  );
}

export default UseMemoDemo;